//
//  YYWebController.swift
//  YYProject
//
//  Created by 陆文宇 on 2017/8/16.
//  Copyright © 2017年 陆文宇. All rights reserved.
//

import UIKit
import WebKit

/// 该类不能由Nib加载
class YYWebController: YYController, WKUIDelegate, WKNavigationDelegate {
    
    deinit {
        yy_webView.scrollView.delegate = nil
        yy_webView.removeObserver(self, forKeyPath: #keyPath(WKWebView.estimatedProgress))
    }
    
    var yy_webView: WKWebView!
    var yy_bridge: THWKWebViewBridge!
    var yy_progressView: UIProgressView!
    var yy_webUrl: String = "" {
        didSet {
            if isViewLoaded {
                yy_load()
            }
        }
    }
        
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        if yy_needRefreshWhenAppear && yy_isViewAppear {
            yy_load()
        }
    }
    
    override func loadView() {
        yy_createWebView()
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        yy_load()
    }
    
    func yy_createProgressView() {
        yy_progressView = UIProgressView(progressViewStyle: .bar)
        yy_progressView.progressTintColor = mainColor
        yy_progressView.frame = CGRect(x: 0, y: 0, width: screenWidth, height: 2)
        yy_webView.addSubview(yy_progressView)
        
        yy_webView.addObserver(self, forKeyPath: #keyPath(WKWebView.estimatedProgress), options: .new, context: nil)
    }
    
    func yy_createWebView() {
        yy_webView = WKWebView.create()
        yy_bridge = THWKWebViewBridge(webView: yy_webView, controller: self)
        yy_registerJS()
        yy_webView.uiDelegate = self
        yy_webView.navigationDelegate = self
        yy_webView.scrollView.delegate = self
        yy_webView.scrollView.showsVerticalScrollIndicator = false
        
        yy_configWebView()
        yy_createProgressView()
        view = yy_webView
    }
    
    func yy_configWebView() {
        
    }
    
    func yy_load() {
        if let url = URL(string: yy_webUrl) {
            yy_webView.load(URLRequest(url: url))
        }
    }
    
    final func yy_registerJS()  {
        yy_registerCommonJs()
        yy_registerOtherJs()
    }
    
    func yy_registerOtherJs() {
        
    }
    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == #keyPath(WKWebView.estimatedProgress) {
            self.yy_progressView.setProgress(Float(change![NSKeyValueChangeKey.newKey] as! Double), animated: true)
        }
    }
    
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        yy_progressView.isHidden = true
        
        if title == nil || title!.isEmpty {
            title = webView.title
        }
    }
    
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        guard navigationAction.request.url != nil else {
            decisionHandler(.cancel)
            return
        }
        
        guard navigationAction.request.url!.absoluteString.hasPrefix(webviewUrlPrex) else {
            decisionHandler(.allow)
            return
        }
        
        let path = navigationAction.request.url!.path
        var webPath = URL(string: yy_webUrl)!.path
        if !webPath.hasPrefix("/") {
            webPath.insert("/", at: webPath.startIndex)
        }
        if path == webPath {
            decisionHandler(.allow)
        } else {
            var params = [String: String]()
            
            if let query = navigationAction.request.url?.query {
                let querys = query.components(separatedBy: "&")
                
                for item in querys {
                    let items = item.components(separatedBy: "=")
                    params[items[0]] = items[1]
                }
            }
            
            YYRouter.pushToVC(of: path, params: params)
            decisionHandler(.cancel)
        }
    }
    
    func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) {
        let alertC = UIAlertController(title: "提示", message: message, preferredStyle: .alert)
        alertC.addAction(UIAlertAction(title: "确定", style: .default, handler: { (_) in
            completionHandler()
        }))
        present(alertC, animated: true, completion: nil)
    }
    
    func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (Bool) -> Void) {
        let alertC = UIAlertController(title: "提示", message: message, preferredStyle: .alert)
        alertC.addAction(UIAlertAction(title: "确定", style: .default, handler: { (_) in
            completionHandler(true)
        }))
        alertC.addAction(UIAlertAction(title: "取消", style: .cancel, handler: { (_) in
            completionHandler(false)
        }))
        present(alertC, animated: true, completion: nil)
    }
    
    func webView(_ webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (String?) -> Void) {
        let alertC = UIAlertController(title: nil, message: prompt, preferredStyle: .alert)
        alertC.addTextField { (tf) in
            tf.text = defaultText
        }
        alertC.addAction(UIAlertAction(title: "确定", style: .default, handler: { (_) in
            completionHandler(alertC.textFields?.first?.text)
        }))
        alertC.addAction(UIAlertAction(title: "取消", style: .cancel, handler: { (_) in
            completionHandler(nil)
        }))
        present(alertC, animated: true, completion: nil)    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
